//JavaScript Framework 2.0 Code
try {
	Type.registerNamespace('com.yonyou.ncmm_pac_pda.PurchaseInScanListPageController');
	com.yonyou.ncmm_pac_pda.PurchaseInScanListPageController = function() {
		com.yonyou.ncmm_pac_pda.PurchaseInScanListPageController.initializeBase(this);
		this.initialize();
	}
	var popDialogInfo = {
		"viewid" : "panel13", //显示的控件的id，通常是一个容器控件div
		"popgravity" : "popbottom", //popcenter|poptop|popbottom|popleft|popright,弹出后最终显示的位置
		istouch : 'false'
	};

	function com$yonyou$ncmm_pac_pda$PurchaseInScanListPageController$initialize() {
		//you can programing by $ctx API
		//get the context data through $ctx.get()
		//set the context data through $ctx.push(json)
		//set the field of the context through $ctx.put(fieldName, fieldValue)
		//get the parameter of the context through $ctx.param(parameterName)
		//Demo Code:
		//    var str = $ctx.getString();      //获取当前Context对应的字符串
		//    alert($ctx.getString())          //alert当前Context对应的字符串
		//    var json = $ctx.getJSONObject(); //获取当前Context，返回值为json
		//    json["x"] = "a";        //为当前json增加字段
		//    json["y"] = [];           //为当前json增加数组
		//    $ctx.push(json);            //设置context，并自动调用数据绑定
		//
		//    put方法需手动调用databind()
		//    var x = $ctx.get("x");    //获取x字段值
		//    $ctx.put("x", "b");     //设置x字段值
		//    $ctx.put("x", "b");     //设置x字段值
		//    $ctx.databind();            //调用数据绑定才能将修改的字段绑定到控件上
		//    var p1 = $param.getString("p1");   //获取参数p2的值，返回一个字符串
		//    var p2 = $param.getJSONObject("p2");   //获取参数p3的值，返回一个JSON对象
		//    var p3 = $param.getJSONArray("p3");   //获取参数p1的值，返回一个数组

		//your initialize code below...

	}

	function com$yonyou$ncmm_pac_pda$PurchaseInScanListPageController$evaljs(js) {
		eval(j)
	}

	/**
	 *返回按钮
	 * @param {Object} sender
	 * @param {Object} args
	 */
	function com$yonyou$ncmm_pac_pda$PurchaseInScanListPageController$button0_onclick(sender, args) {
		$view.close();
	}

	/**
	 * 显示更多菜单
	 * @param {Object} sender
	 * @param {Object} args
	 */
	function showMenuList(sender, args) {
		NCMMPubMenu.openDropDownList("imagebutton1");
	}

	/**
	 * 全选
	 */
	function checkAll(sender, args) {
		$ctx.dataCollect();
		var isChecked = $id(sender).get("checked");
		var sourceData = $ctx.getJSONArray("puinscanlist");
		for (var i = 0; i < sourceData.length; i++) {
			sourceData[i]["isgroupchecked"] = isChecked;

			for (var j = 0; j < (sourceData[i]["row"]).length; j++) {
				((sourceData[i]["row"])[j])["ischecked"] = isChecked;
			}
		}
		var json = {};
		json["puinscanlist"] = sourceData;
		json["checkAll"] = isChecked;
		$ctx.push(json);
		//将数据显示在控件上

	}

	/**
	 * 检测是否需要更新全选标记
	 */
	function checkAllStatus(sender, args) {
		var isCheckedAll = true;
		$ctx.dataCollect();
		var sourceData = $ctx.getJSONArray("puinscanlist");
		for (var i = 0; i < sourceData.length; i++) {
			if (sourceData[i]["ischecked"] == null || sourceData[i]["ischecked"] == false || sourceData[i]["ischecked"] == "false") {
				isCheckedAll = false;
				break;
			}
		}

		$ctx.put("checkAll", isCheckedAll);
		//更新全选复选框的界面显示
		$ctx.dataBind();

	}

	/**
	 * 判断是否需要创建到货单扫描记录表
	 */
	function initScanTable(sender, args) {
		if ($cache.read("isCreatePuInScaneTable") == "true")
			return;
		NCMMPubUtil.dropTable(PurchaseInScanedVO);
		NCMMPubUtil.createTable(PurchaseInScanedVO);
		$cache.write("isCreatePuInScaneTable", "true");
	}

	function loadDataFromLocalDB() {
		if (NCMMPubUtil.isTableExist(PurchaseInVO) == false) {
			return;
		}
		//1 根据vbillcode和行号分组查询vo
		var sql = getQuerySql();
		var data = NCMMPubUtil.queryBySQL(sql);
		data = eval(data);
		//2 根据查询到的数据
		var scangroups = getScanVOsBySql(data);
		//$alert("scangroups="+$jsonToString({scangroups:scangroups}));
		//显示
		$ctx.push({
			"puinscanlist" : scangroups
		});
		//NCMMPubUtil.notifyFilter("search0", "listviewdefine0", ["vbillcode", "materialname"]);
	}

	function getScanVOsBySql(data) {
		var measdocJson = {};
		var rtnarr = new Array();
		Array.prototype.map.call(data, function(vo) {
			var vbillcode = vo[PurchaseInScanedVO.VBILLCODE.name];
			var crowno = vo[PurchaseInScanedVO.CROWNO.name];
			var wheresql = "where " + PurchaseInScanedVO.VBILLCODE.name + "='" + vbillcode + "' and " + PurchaseInScanedVO.CROWNO.name + "='" + crowno + "' ";
			var sum = 0;
			var cunitid = "";
			NCMMPubUtil.queryVO(PurchaseInScanedVO, wheresql, function(subdata) {
				var rowdata = eval(subdata);
				rowdata = NCMMPubUtil.htmlspecialjsonarray2UI(rowdata);
				if (NCMMPubUtil.isNotEmpty(rowdata)) {
					for (var i = 0; i < rowdata.length; i++) {
						var scanednum = rowdata[i][PurchaseInScanedVO.SCANNUM.name];
						//$alert("sum=" + sum.toString() + " scanednum=" + scanednum);
						sum = NCMMPUINUtil.getAddNum(sum, scanednum);

					}
					cunitid = rowdata[0]["cunitid"];
				}
				vo["row"] = rowdata;
				if (NCMMPubUtil.isEmpty(measdocJson) || NCMMPubUtil.isEmpty(measdocJson[cunitid])) {
					var rtn = NCMMPUINUtil.calNumByBitnumber(sum, cunitid);
					if (rtn["flag"]) {
						measdocJson["cunitid"] = rtn["bitnumber"];
						sum = rtn["num"];
					}
				} else {
					var bitnumber = measdocJson[cunitid];
					var rtn = NCMMPUINUtil.toDecimalN(sum, bitnumber);
					if (rtn["flag"]) {
						sum = rtn["num"];
					}
				}
				vo["sumScanedNum"] = sum;
				rtnarr.push(vo);
			});
		});
		return rtnarr;
	}

	function getQuerySql() {
		var sql = "SELECT " + PurchaseInScanedVO.VBILLCODE.name + ", " + PurchaseInScanedVO.CROWNO.name + ", " + PurchaseInScanedVO.MATERIALNAME.name + ", " + PurchaseInScanedVO.SCANNUM.name + " FROM " + PurchaseInScanedVO.prototype.getTableName() + " group by " + PurchaseInScanedVO.VBILLCODE.name + ", " + PurchaseInScanedVO.CROWNO.name;

		return sql;
	}

	function updateScanedNum(row) {
		var id = row["csourcebillbid"];
		var condition = {
			"pkarriveorderb" : id
		};
		NCMMPubUtil.queryVOByConditions(PurchaseInVO, condition, function(data) {
			if (NCMMPubUtil.isEmpty(data)) {
				return;
			}
			var vos = eval(data);
			vos = NCMMPubUtil.htmlspecialjsonarray2UI(vos);
			//$alert("删除前待更新的vo为"+$jsonToString(vos[0]));
			if (NCMMPubUtil.isEmpty(vos)) {
				return;
			}
			var newNum = NCMMPUINUtil.getSubNum(vos[0]["scanednum"], row["scannum"]);
			vos[0]["scanednum"] = newNum;
			//$alert("删除时更新的vo为"+$jsonToString(vos[0]));
			NCMMPubUtil.updateVO(PurchaseInVO, vos[0]);
		});
	}

	function getNumByBit(num, cunitid) {
		var rtn;
		if (!NCMMPubUtil.isEmpty(cunitid)) {
			rtn = NCMMPUINUtil.calNumByBitnumber(num, cunitid);
			if (rtn["flag"]) {
				num = rtn["num"];
			}
		}
		return num;
	}

	function fillBillinfos(headKey, headJson, itemKeyJson, itemJson, bbitemJson) {
		var billinfos = [];
		for (var i = 0; i < headKey.length; i++) {
			var head = headJson[headKey[i]];
			var itemkeys = itemKeyJson[headKey[i]];
			var items = getItems(itemkeys, itemJson, bbitemJson);
			var billinfo = {
				"head" : head,
				"items" : items
			};
			billinfos.push({
				"billinfo" : billinfo
			});
		}
		return billinfos;
	}

	function getItems(itemkeys, itemJson, bbitemJson) {
		var items = [];
		for (var i = 0; i < itemkeys.length; i++) {
			var item = itemJson[itemkeys[i]];
			if (!NCMMPubUtil.isEmpty(bbitemJson) && !NCMMPubUtil.isEmpty(bbitemJson[itemkeys[i]])) {
				//处理bbitem
				var bbitemArr = bbitemJson[itemkeys[i]];
				var bbitems = getBbitems(bbitemArr);
				item["bbitems"] = bbitems;
			}
			items.push({
				"item" : item
			});
		}
		return items;
	}

	function getBbitems(bbitemArr) {
		var bbitems = [];
		for (var i = 0; i < bbitemArr.length; i++) {
			var bbitem = {
				"bbitem" : bbitemArr[i]
			};
			bbitems.push(bbitem);
		}
		return bbitems;
	}

	/**
	 * 提交
	 */
	function submitPuInVOs(sender, args) {
		//测试连接
		NCMMDBUtil.testNCConnection(function(data) {
			if (data == false || data == "false") {
				$toast("连接服务器失败，无法提交扫描记录");
				return;
			} else {//连接验证成功后的后续处理
				$js.showLoadingBar({
					msg : "正在提交数据，请稍后..."
				});
				$ctx.dataCollect();
				var sourceData = $ctx.getJSONArray("puinscanlist");
				var stordoc = $cache.read("defaultstordoc");
				var needDownload = false;
				var billinfos = [];
				var bids = [];
				var headJson = {};
				var itemJson = {};
				var bbitemJson = {};
				var itemKeyJson = {};
				var headKey = [];
				var vos = [];
				var bidAndScanNum = {};
			
				var hidAndNScanNum = {};
				for (var i = 0; i < sourceData.length; i++) {
					//过滤出需要上传的扫描记录
					if (sourceData[i]["isgroupchecked"] != null && (sourceData[i]["isgroupchecked"] == true || sourceData[i]["isgroupchecked"] == "true")) {

						if (NCMMPubUtil.isNotEmpty(sourceData[i]["row"])) {

							for (var j = 0; j < sourceData[i]["row"].length; j++) {
								vos.push(sourceData[i]["row"][j]);
								needDownload = true;
								//选中的vo拼凑billinfos
								var json = sourceData[i]["row"][j];
                                var stordocid;
			                  	if(stordoc == null || stordoc == "") {
				                  if(NCMMPubUtil.isEmpty(json.cwarehouseid)){				   
			                        $js.hideLoadingBar();			   
			                         $alert("默认仓库不能为空，请设置！");
			                        return;
			                       }
			                      else{
			                      stordocid=json.cwarehouseid;
			                     }
		                        }
		                        else{
		                           stordocid=$stringToJSON(stordoc).pk_stordoc;
		                        }
		                      if(NCMMPubUtil.isEmpty(stordocid)){				   
			                    $js.hideLoadingBar();			   
			                    $alert("默认仓库不能为空，请设置！");
			                     return;
			                   }
								var itemKey = json.csourcebillbid + json.vbatchcode;
								bids.push(json.csourcebillbid);

								//处理头map
								if (NCMMPubUtil.isEmpty(headJson) || NCMMPubUtil.isEmpty(headJson[json.csourcebillhid])) {
									var head = {};
									head["csourcebillhid"] = json.csourcebillhid;
									head["cwarehouseid"] = stordocid;
									head["csourceheadts"] = json.csourceheadts;
									headJson[json.csourcebillhid] = head;
									headKey.push(json.csourcebillhid);
									itemKeyJson[json.csourcebillhid] = [];
								}
								//处理体Map
								if (NCMMPubUtil.isEmpty(itemJson) || NCMMPubUtil.isEmpty(itemJson[itemKey])) {
									var item = {};
									item["csourcebillbid"] = json.csourcebillbid;
									item["cmaterialvid"] = json.cmaterialvid;
									item["cunitid"] = json.cunitid;
									item["pk_batchcode"] = json.pk_batchcode;
									item["vbatchcode"] = json.vbatchcode;
									item["ninnum"] = json.scannum;
									item["nassistnum"] = json.scanastnum;
									item["csourcebodyts"] = json.csourcebodyts;
									itemJson[itemKey] = item;
									var newItemKey = itemKeyJson[json.csourcebillhid];
									newItemKey.push(itemKey);
									itemKeyJson[json.csourcebillhid] = newItemKey;
									bidAndScanNum[json.csourcebillbid] = json.scannum;
									
								} else {
									var newItem = itemJson[itemKey];
									newItem.ninnum = NCMMPUINUtil.getAddNum(newItem.ninnum, json.scannum);
									newItem.nassistnum=NCMMPUINUtil.getAddNum(newItem.nassistnum, json.scanastnum);
									itemJson[itemKey] = newItem;
									var oldNum = bidAndScanNum[json.csourcebillbid];
									var newNum = NCMMPUINUtil.getAddNum(oldNum, json.scannum);
									bidAndScanNum[json.csourcebillbid] = newNum;
								}
								if (NCMMPubUtil.isNotEmpty(hidAndNScanNum) && NCMMPubUtil.isNotEmpty(hidAndNScanNum[json.csourcebillbid])) {
									var nScanedNum = NCMMPUINUtil.getAddNum(hidAndNScanNum[json.csourcebillbid], json.scannum);
									hidAndNScanNum[json.csourcebillbid] = nScanedNum;
								} else {
									hidAndNScanNum[json.csourcebillbid] = json.scannum;
								}
								//处理序列号
								if (!NCMMPubUtil.isEmpty(json.vserialcode)) {
									var bbitem = {};
									bbitem["vserialcode"] = json.vserialcode;
									bbitem["ninnum"] = json.scannum;
									bbitem["nassistnum"] = json.scanastnum;
									if (NCMMPubUtil.isEmpty(bbitemJson) || NCMMPubUtil.isEmpty(bbitemJson[itemKey])) {
										bbitemJson[itemKey] = [bbitem];
									} else {
										var newBbitem = bbitemJson[itemKey];
										newBbitem.push(bbitem);
										bbitemJson[itemKey] = newBbitem;
									}
								}
							}
						}
					}
				}
				if (needDownload == false) {
					$js.hideLoadingBar();
					$toast("没有选中扫描记录！");
					return;
				}
				billinfos = fillBillinfos(headKey, headJson, itemKeyJson, itemJson, bbitemJson);
				// $alert("billinfos="+$jsonToString(billinfos));
				//上传扫描记录生产采购入库单
				NCMMDBUtil.submitLocaldataToNC("23_45save", billinfos, function(data) {
					if (data != null && data != "") {
						// $alert("返回数据="+$jsonToString({"data":data}));
						if (data.return == null || data.return == "") {
							$js.hideLoadingBar();
							$alert($jsonToString(data));
							return;
						} else if (data.return.returnFlag == 1) {
							var where = "where pkarriveorderb in (";
							for (var i = 0; i < bids.length; i++) {
								where = where + "'" + bids[i] + "' ,"
							}
							where = where.slice(0, -1) + ")";
							//从本地数据中查询出所有行id 然后根据行id和提交数量之间的关系 从扫描数量中减去提交数量 当数量为0时 删除本地数据
							NCMMPubUtil.queryVO(PurchaseInVO, where, function(data) {
								if (NCMMPubUtil.isEmpty(data)) {
									$js.hideLoadingBar();
									return;
								} else {
									var puinvos = eval(data);
									puinvos = NCMMPubUtil.htmlspecialjsonarray2UI(puinvos);
									for (var i = 0; i < puinvos.length; i++) {
										var id = puinvos[i]["pkarriveorderb"];
										var updateNum = hidAndNScanNum[id];
										puinvos[i]["scanednum"] = NCMMPUINUtil.getSubNum(puinvos[i]["scanednum"], updateNum);
										puinvos[i]["nnum"] = NCMMPUINUtil.getSubNum(puinvos[i]["nnum"], updateNum);
										var nastnum = NCMMPUINUtil.getNastum(puinvos[i]["nnum"], puinvos[i]["vchangerate"]);
										var bitnumber = 0;
										try {
											bitnumber = puinvos[i]["scanednum"].toString().split(".")[1].length
										} catch(e) {
											bitnumber = 0
										}
										if (bitnumber > 0) {
											nastnum = nastnum.toFixed(bitnumber);
										}
										puinvos[i]["nastnum"] = nastnum;
										if (puinvos[i]["nnum"] <= 0 || puinvos[i]["nastnum"] <= 0) {
											NCMMPubUtil.deleteVO(PurchaseInVO, puinvos[i])
										} else {
											NCMMPubUtil.updateVO(PurchaseInVO, puinvos[i]);
										}
									}
								}
							});
							//删除本地扫描数据
							for (var i = 0; i < vos.length; i++) {
								NCMMPubUtil.deleteVO(PurchaseInScanedVO, vos[i]);
							}
							//从本地加载数据
							loadDataFromLocalDB();
							$js.hideLoadingBar();
							//显示提交成功，
							$toast("提交成功！");
						} else {
							$js.hideLoadingBar();
							$alert($jsonToString(data));
							return;
						}
					} else {
						$js.hideLoadingBar();
						$alert("上传失败");
						return;
					}
				});
			}
		});

	}

	function search(sender, args) {
		NCMMPubUtil.quickFilter();

	}

	/**
	 * 详情按钮
	 */
	function showScanDetail() {
		$view.closePop(popDialogInfo);
		var row = $id("listviewdefine0").get("row");
		//row = $stringToJSON(row);
		$view.open({
			"viewid" : "com.yonyou.ncmm_pac_pda.PurchaseInScanDetailPage", //目标页面（首字母大写）全名
			"isKeep" : "true", //打开新页面的同时是否保留当前页面，true为保留，false为不保留
			"row" : row
		})

	}

	/**
	 * 修改按钮
	 */
	function openScanEditPage() {
		$view.closePop(popDialogInfo);
		var row = $id("listviewdefine0").get("row");
		//row = $stringToJSON(row);
		$view.open({
			"viewid" : "com.yonyou.ncmm_pac_pda.PurchaseInScanEditPage", //目标页面（首字母大写）全名
			"isKeep" : "true", //打开新页面的同时是否保留当前页面，true为保留，false为不保留
			"scanlistrow" : row
		})
	}

	/**
	 * 删除按钮
	 */
	function itemDelete(sender, args) {
		$view.closePop(popDialogInfo);
		var params = {
			"title" : "提示",
			"message" : "确定删除所选记录吗？",
			"okbuttontitle" : "确定",
			"cancelbuttontitle" : "取消",
			"style" : "ok-cancel",
			"okaction" : "doDelete()",
			"cancelaction" : "doCancel()"
		};
		$view.openDialog(params);
	}

	function doCancel() {
		$toast("清除操作已取消。");
	}

	//执行清除操作
	function doDelete() {
		var row = $id("listviewdefine0").get("row");
		row = $stringToJSON(row);
		//删除之前需要更新扫码记录
		updateScanedNum(row);
		NCMMPubUtil.deleteVO(PurchaseInScanedVO, row);
		loadDataFromLocalDB();
	}

	/**
	 * 取消按钮
	 */
	function itemCancle() {
		$view.closePop(popDialogInfo);
	}

	function onEventClick_checkRow(sender, args) {
		$ctx.dataCollect();
		var isCheckedAll = true;

		var sourceData = $ctx.getJSONArray("puinscanlist");
		for (var i = 0; i < sourceData.length; i++) {
			if (sourceData[i]["isgroupchecked"] == null || sourceData[i]["isgroupchecked"] == false || sourceData[i]["isgroupchecked"] == "false") {
				isCheckedAll = false;
				for (var j = 0; j < (sourceData[i]["row"]).length; j++) {
					((sourceData[i]["row"])[j])["ischecked"] = false;
				}
			} else {
				for (var j = 0; j < (sourceData[i]["row"]).length; j++) {
					((sourceData[i]["row"])[j])["ischecked"] = true;
				}
			}
		}
		$ctx.put("checkAll", isCheckedAll);
		//更新全选复选框的界面显示
		$ctx.put("puinscanlist", sourceData);
		$ctx.dataBind();

	}

	function onEventLoad_showScan(sender, args) {
		loadDataFromLocalDB();
	}

	function onItemClick_showDetailInfo(sender, args) {
		//如果点击的是组列表，则不弹出浮动按钮组
		var row = {};
		row = $id("listviewdefine0").get("row");
		row = $stringToJSON(row);
		if (row && row["row"])
			return;
		$view.openPop(popDialogInfo);

	}

	function onRestart_loadData(sender, args) {
		loadDataFromLocalDB();

	}
	com.yonyou.ncmm_pac_pda.PurchaseInScanListPageController.prototype = {

		button0_onclick : com$yonyou$ncmm_pac_pda$PurchaseInScanListPageController$button0_onclick,
		initialize : com$yonyou$ncmm_pac_pda$PurchaseInScanListPageController$initialize,
		evaljs : com$yonyou$ncmm_pac_pda$PurchaseInScanListPageController$evaljs
	};
	com.yonyou.ncmm_pac_pda.PurchaseInScanListPageController.registerClass('com.yonyou.ncmm_pac_pda.PurchaseInScanListPageController', UMP.UI.Mvc.Controller);
} catch(e) {
	$e(e);
}